﻿#ifndef CL2CRSDRIVECONTROL_H
#define CL2CRSDRIVECONTROL_H
#include "Head.h"
#include <QObject>
#include <QTimer>
#include <QMap>

#include "BaseMotorController.h"
#include "BaseModbus.h"

#define RETRYTIMES     5                //移动位置失败，重新尝试移动的次数
#define DRIVER_SUBDIVISION   10000

//不成熟的控制类
class CL2CRSDriveControl final: public BaseMotorController
{
    Q_OBJECT
public:
    Q_INVOKABLE explicit CL2CRSDriveControl(QObject *parent = 0);

    ~CL2CRSDriveControl();

public:
    // BaseMotorController
    virtual void SetCurrentAxisType(AxisType axisType) override;

    virtual void SetMotorEnable(bool enable) override;

    int SetVelocity(VEL_TYPE_ENUM eVelType, double dVelocity) override;//设置轴的速度                              //停止运动
    int RelativeMove(double dRelativeMove) override;   //设置轴的相对移动位置
    int AbsoluteMove(double dMove) override;
    int SetCurrentPositionToZero() override;                                  //设置轴的位置归零,感应限位0
    int GetPosition(double &dPosition) override;                //获取当前轴的位置

    int SetElectricityPercentage(int percentage);

    virtual void SetLimit(QList<MotorIOItem> items) override;

    virtual void ReturnToZero(DirectionType direction, LimitType limit) override;

    virtual void SetMaxElectricity(int electricity) override;

    //设置导轨方向
    virtual void SetAxisDriection(AxisDirectionType axisType) override;

    virtual QList<StateItem> GetStateItems() override;

    bool Stop() override;

    virtual bool SaveParam() override;

    virtual bool Reset() override;

private:

private:
    QList<BaseModbus*> _myModbus;
    BaseMotorController::AxisType _currentAxisType=AxisType::AXIS_X;

    QMap<VEL_TYPE_ENUM,int> _typeAddressMap;
    QList<StateItem> _stateItems;

    bool WriteRegister(int addr,uint16_t value);
    bool WriteRegisters(int addr, QList<uint16_t> value);
    bool ReadOutRegisters(int addr, int count, QList<uint16_t> &value);
    bool ReadOutRegister(int addr, uint16_t &value);

    QList<uint16_t> ConvertToUint16List(int data);

    BaseModbus *GetCurrentModbus();
public:
    void SetCommunication(QList<BaseCommunication *> communication) override;

    // BaseDevice interface
protected:
    virtual void GetConnectStateCore(DeviceStateItems &items) override final;
};

#endif // CL2CRSDRIVECONTROL_H
